package org.rency.common.memcache.core;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.rency.common.memcache.MemcacheDict;
import org.rency.common.memcache.bean.MemcacheNode;
import org.rency.common.memcache.repository.NodeRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.auth.AuthInfo;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.utils.XMemcachedClientFactoryBean;

public class MemcachedClientFactoryBean extends XMemcachedClientFactoryBean implements MemcachedClientFactory,InitializingBean{

	private final Logger logger = LoggerFactory.getLogger(MemcachedClientFactoryBean.class);
	
	@Resource(name="nodeRepository")
	private NodeRepository nodeRepository;
	
	private MemcachedClient memcachedClient;
	
	private String userName;
	private String passwd;
	private Integer compressionThreshold;
	
	@Override
	public Object getObject() throws Exception {
		if(memcachedClient == null){
			memcachedClient = (MemcachedClient) super.getObject();
			memcachedClient.getTranscoder().setCompressionThreshold(compressionThreshold);
		}
		return this;
	}
	
	@Override
	public MemcachedClient getClient() {
		return memcachedClient;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		List<MemcacheNode> nodes = nodeRepository.loadAll();
		if(CollectionUtils.isEmpty(nodes)){
			throw new RuntimeException("未读取到Memcached节点配置信息.");
		}
		StringBuilder nodeHost = new StringBuilder();
		List<Integer> weights = new ArrayList<Integer>(nodes.size());
		Map<InetSocketAddress, AuthInfo> authInfoMap = new HashMap<InetSocketAddress, AuthInfo>();
		AuthInfo authInfo = AuthInfo.typical(userName, passwd);
		for(MemcacheNode node : nodes){
			//认证信息
			authInfoMap.put(new InetSocketAddress(node.getNodeHost(),node.getNodePort()), authInfo);
			nodeHost.append(node.getNodeHost()+":"+node.getNodePort());
			nodeHost.append(" ");
			weights.add(node.getNodeWeight());
			logger.info("加载Memcached节点配置[{}].",node);
		}
		super.setServers(nodeHost.toString().trim());
		super.setWeights(weights);
		super.setName(MemcacheDict.DEFAULT_MEMCACHE_CLIENT_NAME);
		super.setCommandFactory(new BinaryCommandFactory());
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public Integer getCompressionThreshold() {
		return compressionThreshold;
	}

	public void setCompressionThreshold(Integer compressionThreshold) {
		this.compressionThreshold = compressionThreshold;
	}


}